from app.libs.redprint import RedPrint
from app.validators.book import SearchFrom
from app.models.book import Book
from sqlalchemy import or_
from flask import jsonify

# 注册红图
api = RedPrint('book')


@api.route('/search', methods=['GET'])
def search():
    form = SearchFrom().validate_for_api()
    q = '%' + form.q.data + '%'
    books = Book.query.filter(
        or_(
            Book.title.like(q), Book.publisher.like(q)
        )
    ).all()
    books = [book.hide('id', 'summary') for book in books]
    return jsonify(books)


@api.route('/<isbn>/detail', methods=['GET'])
def detail(isbn):
    book = Book.query.filter_by(isbn=isbn).first_or_404()
    return jsonify(book)


@api.route('', methods=['GET'])
def get_book():
    return 'get book'


@api.route('', methods=['POST'])
def create_book():
    return 'get book'
